package mia.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import mia.entity.UserEntity;
import mia.util.HibernateManager;

public class UserEntityDAO {

	public static boolean checkIfUserExists(String login, String email)
	{
		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(UserEntity.class);
		crit.add(
					Restrictions.or(
							(Restrictions.eq("login", login)),
							(Restrictions.eq("email", email))
					)
				);
		@SuppressWarnings("unchecked")
		List<UserEntity> lista = crit.list();
		session.close();
		if(lista.size() > 0)
			return true;
		else
			return false;
	}
	
	public static boolean checkIfLoginAndPasswordCorrect(String login, String password)
	{
		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(UserEntity.class);
		crit.add(
					Restrictions.and(
							(Restrictions.eq("login", login)),
							(Restrictions.eq("password", password))
					)
				);
		
		@SuppressWarnings("unchecked")
		List<UserEntity> list = (List<UserEntity>)crit.list();
		session.close();
		if(list.size() > 0)
			return true;
		else
			return false;
	}
	public static UserEntity getUserByLogin(Session session, String login)
	{
		Criteria crit = session.createCriteria(UserEntity.class);
		crit.add(Restrictions.eq("login", login));
		@SuppressWarnings("unchecked")
		List<UserEntity> lista = crit.list();
		if(lista.size() > 0)
		{
			UserEntity result = lista.get(0);
			if(result.getFirstName() == null)
				result.setFirstName("");
			if(result.getLastName() == null)
				result.setLastName("");
			if(result.getPhoneNumber() == null)
				result.setPhoneNumber("");
			return result;
		}
		else
			return null;
	}
	
	public static List<UserEntity> searchUsers(String login, String imie, String nazwisko, String email, String phone)
	{
		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(UserEntity.class);
		
		if(login != null && login != "")
			crit.add(Restrictions.like("login", "%"+login+"%"));
		if(imie != null && imie != "")
			crit.add(Restrictions.like("firstName", "%"+imie+"%"));
		if(nazwisko != null && nazwisko != "")
			crit.add(Restrictions.like("lastName", "%"+nazwisko+"%"));
		if(email != null && email != "")
			crit.add(Restrictions.like("email", "%"+email+"%"));
		if(phone != null && phone != "")
			crit.add(Restrictions.like("phoneNumber", "%"+phone+"%"));
		
		@SuppressWarnings("unchecked")
		List<UserEntity> lista = crit.list();
		return lista;
	}
}
